﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;

using zijian666.Converts.Abstractions;

namespace zijian666.Converts.Translator;

/// <summary>
/// 操作可循环对象的翻译器
/// </summary>
public class EnumeratorTranslator : ITranslator
{
    /// <inheritdoc />
    public bool CanTranslate(Type type)
        => type != typeof(string)
        && (typeof(IEnumerable).IsAssignableFrom(type)
        || typeof(DataRow).IsAssignableFrom(type)
        || typeof(DataRowView).IsAssignableFrom(type)
        || typeof(DataTable).IsAssignableFrom(type)
        || typeof(IListSource).IsAssignableFrom(type));

    /// <inheritdoc />
    public object? Translate(IConvertContext context, object input)
        => input switch
        {
            string => null,
            IEnumerable enumerable => enumerable.GetEnumerator(),
            DataRow dataRow => dataRow.ItemArray.GetEnumerator(),
            DataRowView dataRowView => dataRowView.Row?.ItemArray.GetEnumerator(),
            DataTable dataTable => dataTable.Rows.GetEnumerator(),
            IListSource listSource => listSource.GetList()?.GetEnumerator(),
            _ => null,
        };
}
